let Koa = require('koa');
let app = new Koa();
let bodyparser = require('koa-bodyparser');
let router = require('koa-router')();
let query = require('./sql/sql');
let crypto = require('crypto');
router.post('/login', async ctx => {
    let { user, pwd } = ctx.request.body;
    let newpwd = crypto.createHash('md5').update(pwd).digest('hex')
    let res = await query(`select * from addr_user where user='${user}'`);
    if (res.length) {
        if (newpwd == res[0].pwd) {
            ctx.body = {
                code: 1,
                msg: '登陆成功',
                id: res[0].id
            }
        } else {
            ctx.body = {
                code: 0,
                msg: '密码错误'
            }
        }
    } else {
        ctx.body = {
            code: 0,
            msg: '该用户未注册'
        }
    }

})
router.post('/regisity', async ctx => {
    let { user, pwd } = ctx.request.body;
    let res = await query(`select * from addr_user where user='${user}'`);
    if (res.length) {
        ctx.body = {
            code: 0,
            msg: '该用户已注册'
        }
    } else {
        let newpwd = crypto.createHash('md5').update(pwd).digest('hex')
        await query(`insert into addr_user (user,pwd) values('${user}','${newpwd}')`);
        let res = await query(`select * from addr_user where user='${user}'`);
        ctx.body = {
            code: 1,
            msg: '注册成功',
            id: res[0].id
        }


    }

})

router.get('/list', async ctx => {
    console.log(ctx.query);
    let { id } = ctx.query;
    let res = await query(`select * from addr_addrs where userid=${Number(id)}`);
    console.log(res)
    ctx.body = {
        code: 1,
        data: res
    }
})

router.post('/add', async ctx => {
    let { userid, name, tel, addr } = ctx.request.body;
    await query(`insert into addr_addrs (userid,name,tel,addr) values(${Number(userid)},'${name}','${tel}','${addr}')`);
    ctx.body = {
        code: 1,
        msg: '添加成功'
    }


})

router.get('/delete', async ctx => {
    let { id } = ctx.query;
    await query(`delete from addr_addrs where id=${Number(id)}`);
    ctx.body = {
        code: 1,
        msg: '删除成功'
    }
})

router.post('/echo', async ctx => {
    let { id } = ctx.request.body;
    let res = await query(`select * from addr_addrs where id=${Number(id)}`);
    ctx.body = {
        code: 1,
        data: res
    }
})

router.post('/edit', async ctx => {
    let { id, name, tel, addr } = ctx.request.body;
    await query(`update addr_addrs set name='${name}',tel='${tel}',addr='${addr}' where id=${Number(id)}  `);
    ctx.body = {
        code: 1
    }
})

app.use(bodyparser());
app.use(router.routes(), router.allowedMethods())

app.listen(3030);